package com.black.cat.jvm.instructions.base;

import com.black.cat.jvm.rtda.Frame;
import com.black.cat.jvm.rtda.JThread;
import com.black.cat.jvm.rtda.heap.methodarea.JClass;
import com.black.cat.jvm.rtda.heap.methodarea.JMethod;

/**
 * @Author blackcat
 * @create 2021/8/16 15:31
 * @version: 1.0
 * @description:
 */
public class ClassInitLogic {

    public static void initClass(JThread thread, JClass clazz) {
        clazz.startInit();
        scheduleClinit(thread, clazz);
        initSuperClass(thread, clazz);
    }

    private static void scheduleClinit(JThread thread, JClass clazz) {
        JMethod clinit = clazz.getClinitMethod();
        if (null == clinit) return;
        Frame newFrame = thread.newFrame(clinit);
        thread.pushFrame(newFrame);
    }

    private static void initSuperClass(JThread thread, JClass clazz) {
        if (clazz.isInterface()) return;
        JClass superClass = clazz.superJClass;
        if (null != superClass && !superClass.initStarted()) {
            initClass(thread, superClass);
        }
    }
}
